package com.lzh.persevere.task;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lzh.persevere.config.constant.SystemInfoConstants;
import com.lzh.persevere.mapper.ArticleInfoMapper;
import com.lzh.persevere.mapper.CategoryInfoMapper;
import com.lzh.persevere.mapper.SystemInfoMapper;
import com.lzh.persevere.model.entity.CategoryInfo;
import com.lzh.persevere.model.entity.SystemInfo;
import com.lzh.persevere.service.SystemInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class SystemInfoTask {

    @Resource
    private ArticleInfoMapper articleInfoMapper;

    @Resource
    private SystemInfoService systemInfoService;

    @Resource
    private SystemInfoMapper systemInfoMapper;

    @Resource
    private CategoryInfoMapper categoryInfoMapper;

    /**
     * 更新文章统计信息 - 2小时执行一次
     */
    @Scheduled(fixedDelay = 1000 * 60 * 60 * 2)
    public void statisticsSystemInfo() {
        log.info("SystemInfoTask statisticsSystemInfo execute...");

        // 文章总数、文章总浏览量
        Map<String, Object> statisticsInfoMap = articleInfoMapper.selectArticleStatisticsInfo();
        List<SystemInfo> systemInfoList = systemInfoMapper.selectByTypeList(Arrays.asList(
                SystemInfoConstants.TOTAL_ARTICLE_COUNT,
                SystemInfoConstants.TOTAL_ARTICLE_VIEW_COUNT
        ));
        for (SystemInfo systemInfo : systemInfoList) {
            Object obj = statisticsInfoMap.get(systemInfo.getType());
            systemInfo.setSystemValue(obj.toString());
        }
        // 分类总数
        Long categoryCount = categoryInfoMapper.selectCount(Wrappers.<CategoryInfo>lambdaQuery().eq(CategoryInfo::getOpenFlag, 1));
        SystemInfo categoryCountSystemInfo = systemInfoMapper.selectEntityByType(SystemInfoConstants.TOTAL_CATEGORY_COUNT);
        categoryCountSystemInfo.setSystemValue(categoryCount.toString());
        systemInfoList.add(categoryCountSystemInfo);

        systemInfoService.updateBatchById(systemInfoList);

    }
}
